<?php

/**
 * @Author:      lyt
 * @DateTime:    2016-02-17 15:28:45
 * @Description: 用于 门店的 仓库的操作
 */
class ScsDatabaseController extends BaseController
{
    /**
     * @Author:      lyt
     * @DateTime:    2016-02-17 15:30:12
     * @Description: 仓库的列表
     */
    
    public function lists(){
    	$validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
    	do{
    		if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $dbs=MainDateBase::getDateByShop($sc_user->shop_id);
            if(sizeof($dbs)<=0){
                MainDateBase::initDateShop($sc_user->shop_id);
                $dbs=MainDateBase::getDateByShop($sc_user->shop_id);
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>sizeof($dbs),"db_info"=>$dbs));
    	}while(false);
    	Log::info("info", array("system" => "scs" ,"event" => "lists", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-02-18 14:03:13
     * @Description: 用于展示 用户的入库单
     */
    public function storageList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);
            $msl=MaintenanceStorageList::leftJoin("sc_user",'sc_user.id','=','maintenance_storage_list.cust_id')->
            leftJoin("maintenance_supplier",'maintenance_supplier.id','=','maintenance_storage_list.supplier')->
            where("maintenance_storage_list.shop_id",$sc_user->shop_id)->orderBy("maintenance_storage_list.created_at",'desc');
            if(Input::get("type")!=""){
                $msl=$msl->where("maintenance_storage_list.type",Input::get("type"));
            }
            if(Input::get("status")!=""){
                $msl=$msl->where("maintenance_storage_list.status",Input::get("status"));
            }
            if(Input::get("date")!=""){
                $msl=$msl->where("maintenance_storage_list.date",Input::get("date"));
            }
            if(Input::get("list_id")!=""){
                $msl=$msl->where("maintenance_storage_list.id","like","%".Input::get("list_id")."%");
            }
            //添加是否含税筛选条件
            if (Input::get('tax') != '') {
                $msl = $msl->where('maintenance_storage_list.tax', Input::get('tax'));
            }
            //添加物流运送税筛选条件
            if (Input::get('logistics_freight') != '') {
                $msl = $msl->where('maintenance_storage_list.logistics_freight', Input::get('logistics_freight'));
            }
            //添加结算方式税筛选条件
            if (Input::get('pay_type') != '') {
                $msl = $msl->where('maintenance_storage_list.pay_type', Input::get('pay_type'));
            }
            if(Input::get("implement_time")!=""){
                $it=Input::get('implement_time');
                $start_time=$it.' 00:00:00';
                $end_time=$it.' 23:59:59';
                $start_time=date("Y-m-d H:i:s",strtotime($start_time)-Config::get("config.report_time_diff"));
                $end_time=date("Y-m-d H:i:s",strtotime($end_time)-Config::get("config.report_time_diff"));
                $msl=$msl->whereBetween("maintenance_storage_list.implement_time",array($start_time,$end_time));
            }
            if(Input::get("supplier")!=""){
                $msl=$msl->where("maintenance_storage_list.supplier",Input::get('supplier'));
            }
            $count=$msl->count();
            $msl=$msl->skip($page_size*($page-1))->take($page_size)->select("maintenance_storage_list.*","maintenance_supplier.name as suppliername","sc_user.real_name")->get();
            foreach ($msl as $_msl) {
                if($_msl->type==2){
                    if($_msl->methed==1){
                        $department=Department::find($_msl->consuming_id);
                        $_msl->shop_name=$department->name;
                    }elseif($_msl->methed==3){
                        if($_msl->shop_type==1){
                            if($_msl->user_type=1){
                                $sc=SCUser::find($_msl->consuming_id);
                                $_msl->shop_name=$sc->real_name;
                            }else{
                                $me=MaintenanceEngineers::find($_msl->consuming_id);
                                $_msl->shop_name=$me->name;
                            }
                        }else{
                            $department=Department::find($_msl->consuming_id);
                            $_msl->shop_name=$department->name;
                        }
                    }else{
                        $ms=MaintenanceShops::find($_msl->consuming_id);
                        $_msl->shop_name=$ms->name;
                    }
                }
                if($_msl->implement_time){
                    $_msl->implement_time=date("Y-m-d H:i:s",strtotime($_msl->implement_time)+Config::get("config.report_time_diff"));    
                }                
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"msl_info"=>$msl));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "storageList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
      * @Author:      lyt
      * @DateTime:    2016-02-26 13:41:16
      * @Description: 入库单的详情
      */
    public function storage(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $msl=MaintenanceStorageList::leftJoin("sc_user",'sc_user.id','=','maintenance_storage_list.cust_id')->
            leftJoin("maintenance_supplier",'maintenance_supplier.id','=','maintenance_storage_list.supplier')->
            leftJoin("department",'department.id','=','maintenance_storage_list.consuming_id')->
            where("maintenance_storage_list.id",Input::get("id"))->where("maintenance_storage_list.shop_id",$sc_user->shop_id)->select("maintenance_storage_list.*","maintenance_supplier.name as suppliername","sc_user.real_name")->first();
            if($msl->type==2){
                if($msl->methed==1){
                    $department=Department::find($msl->consuming_id);
                    $msl->shop_name=$department->name;
                }elseif($msl->methed==3){
                    if($msl->shop_type==1){
                        if($msl->user_type==1){
                            $sc=SCUser::find($msl->consuming_id);
                            $msl->shop_name=$sc->real_name;
                        }else{
                            $me=MaintenanceEngineers::find($msl->consuming_id);
                            $msl->shop_name=$me->name;
                        }
                    }elseif($msl->shop_type==2){
                        $department=Department::find($msl->consuming_id);
                        $msl->shop_name=$department->name;
                    }
                }else{
                    $ms=MaintenanceShops::find($msl->consuming_id);
                    $msl->shop_name=$ms->name;
                }
            }
            if($msl){
                // $total=MaintenanceStorageItem::leftJoin("sc_user",'sc_user.id','=','maintenance_storage_item.own_id')->
                // leftJoin("supply_subject",'supply_subject.id','=','maintenance_storage_item.subject')->
                // leftJoin("maintenance_datebase",'maintenance_datebase.id','=','maintenance_storage_item.data_id')->
                // where("maintenance_storage_item.list_id",$msl->id)->where("maintenance_storage_item.status","!=",2)->sum('tax_purchase_subtotal');
                // $msl->total=bcdiv($total,100,4);
                $total_t=0;  //含税价总计
                $total_number=0; //数量总计
                $class_one_info = [];
                $msi=MaintenanceStorageItem::leftJoin("sc_user",'sc_user.id','=','maintenance_storage_item.own_id')
                    // ->leftJoin("supply_subject",'supply_subject.id','=','maintenance_storage_item.subject')
                    ->leftJoin("maintenance_datebase",'maintenance_datebase.id','=','maintenance_storage_item.data_id')
                    ->where("maintenance_storage_item.list_id",$msl->id)->where("maintenance_storage_item.status","!=",2)
                    ->orderBy('maintenance_storage_item.created_at','desc')
                    ->select("maintenance_storage_item.*","sc_user.real_name","maintenance_datebase.name as data_name")->get();
                $msl->implement_time=isset($msl->implement_time)?date("Y-m-d H:i:s",strtotime($msl->implement_time)+Config::get("config.report_time_diff")):"";
                foreach ($msi as $_msi) {
                    $_msi->implement_time=isset($_msi->implement_time)?date("Y-m-d H:i:s",strtotime($_msi->implement_time)+Config::get("config.report_time_diff")):"";
                    // if($_msi->item_type==0){//如果是标准耗材
                        $item_info=SupplyItem::getCacheItemInfo($_msi->item_id);
                        $scf=SupplyClassification::getClassification($item_info->st_classifi_id);
                        $_msi->subject_name=isset($item_info)?$item_info->scf_name:"";
                        $_msi->scf_name=isset($item_info)?$item_info->scf_name:"";
                        $_msi->item_brand_name=$item_info->brand_name;
                        $_msi->item_series_name=$item_info->series_name;
                        $_msi->item_model_name=$item_info->model;
                        $_msi->item_specification=$item_info->specification;
                        $_msi->item_pack_unit=$item_info->pack;
                        $_msi->item_sale_unit=$item_info->unit;
                        $_msi->two_id=$scf->two_id;
                        $_msi->two=$scf->two;
                        $_msi->one_id=$scf->one_id;
                        $_msi->one=$scf->one;
                        $_msi->goods_name=$item_info->name;
                        $_msi->car_model_comments=$item_info->car_model_comments;
                        $_msi->item_name=$item_info->name;
                    // }else{
                    //     $item_info=SupplyItemNonStandard::getCacheItemInfo($_msi->item_id);
                    //     $scf=StatisticalClassification::getClassification($item_info->st_classifi_id);
                    //     $_msi->scf_name=isset($item_info)?$item_info->scf_name:"";
                    //     $_msi->item_brand_name=$item_info->brand_name;
                    //     $_msi->item_series_name=$item_info->series_name;
                    //     $_msi->item_model_name=$item_info->model;
                    //     $_msi->item_specification=$item_info->specification;
                    //     $_msi->item_pack_unit=$item_info->pack_unit;
                    //     $_msi->item_sale_unit=$item_info->unit;
                    //     $_msi->two_id=$scf->two_id;
                    //     $_msi->two=$scf->two;
                    //     $_msi->one_id=$scf->one_id;   //一级分类的id
                    //     $_msi->one=$scf->one;
                    //     $_msi->use_status=$item_info->use_status;
                    //     $_msi->car_model_comments=$item_info->car_model;
                    //     $_msi->goods_name=$item_info->scf_name.$item_info->series_name.$item_info->model.$item_info->specification;
                        
                    // }
                    $_msi->tax_purchase_price=round(bcdiv($_msi->tax_purchase_price,100,6),2);
                    $_msi->no_tax_purchase_price=round(bcdiv($_msi->no_tax_purchase_price,100,6),2);
                    $_msi->tax_purchase_subtotal=round(bcdiv($_msi->tax_purchase_subtotal,100,6),2);
                    $total_t += $_msi->tax_purchase_subtotal;
                    $total_number += $_msi->number;
                    if(!isset($class_one_info[$_msi->one_id])){ //如果没有一类ID，创建。如果有则相加
                        $class_one_info[$_msi->one_id]['one_id'] = $_msi->one_id;
                        $class_one_info[$_msi->one_id]['name'] = $scf->one;
                        $class_one_info[$_msi->one_id]['number'] = $_msi->number;
                        $class_one_info[$_msi->one_id]['tax_purchase_subtotal'] = $_msi->tax_purchase_subtotal;
                    } else {
                        $class_one_info[$_msi->one_id]['number'] += $_msi->number;
                        $class_one_info[$_msi->one_id]['tax_purchase_subtotal'] += $_msi->tax_purchase_subtotal;
                    }
                }
                $msl->total=$total_t;
                $msl->item=$msi;
                $msl->total_number = $total_number;
                $msl->class_one_info = array_values($class_one_info);
            }else{
                $response = Lang::get("scs_error.maintenance_storage_notexit_60000");
                break;
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("msl_info"=>$msl));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "storageList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-02-26 17:36:11
     * @Description: 用于添加入库单的耗材查询
     */
    public function getSupply(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }

            $car_retrieval_code=Input::get("car_retrieval_code");
            $type=Input::get("type");
            $search_retrieval_code=Input::get("retrieval_code");
            $car_str=Input::get("car_str");
            if($type||$search_retrieval_code||$car_str){
                // $non_ids=SupplyItemNonStandard::retrievalCode($sc_user->shop_id,$car_retrieval_code,$type,$search_retrieval_code,$car_str);//获得非标的耗材id范围
                $si_ids=SupplyItem::retrievalCode($car_retrieval_code,$type,$search_retrieval_code,$car_str);//获得标准的耗材id范围
            }


            $si_sql="select si.id,'' car_model,si.car_model_comments,si.code,si.old_code,si.retrieval_code,si.name,sb.brand_name,ss.name series_name,si.model,supply_classification.name subject_name,si.type,mw.id mw_id,mw.number ,supply_classification.id as scf_id,
                sb.brand_name item_brand_name,ss.name item_series_name,si.model item_model_name,si.volume_size as item_pack_unit,supply_unit.name item_sale_unit,'' as item_specification,
                supply_classification.name as scf_name ,sl.location,si.name as item_name
                from supply_item si
                LEFT JOIN anhui_data.supply_series ss on ss.id=si.series_id
                LEFT JOIN anhui_data.supply_brand sb on sb.id=si.brand_id    
                LEFT JOIN anhui_data.supply_unit  on supply_unit.id=si.sale_unit_id  
                left join supply_classification on supply_classification.id=si.supply_classification_id
                LEFT JOIN (select * from maintenance_warehouse where shop_id=?) mw on mw.item_id=si.id
                LEFT JOIN (select item_id,location from supply_location where shop_id=?) sl on sl.item_id=si.id
                where si.`status`=1";
            if(isset($si_ids)){
                $si_ids[]=0;
                $si_sql.=" and si.id in (".implode(",",$si_ids).")";
            }
            // $sins_sql="select sins.id,sins.car_model,sins.car_model as car_model_comments,sins.`code`,sins.old_code,sins.retrieval_code,sins.name,sins.brand_name,sins.series_name,sins.model,ss.`name` subject_name,1 type,mw.id mw_id,mw.number ,statistical_classification.id as scf_id,
            //     sins.brand_name item_brand_name,sins.series_name item_series_name,sins.model item_model_name,sins.pack_unit item_pack_unit,sins.unit item_sale_unit,sins.specification item_specification,
            //     statistical_classification.name as scf_name from supply_item_non_standard sins
            //     LEFT JOIN supply_subject ss on sins.`subject`=ss.id
            //     left join statistical_classification on statistical_classification.id=sins.st_classifi_id
            //     LEFT JOIN (select * from maintenance_warehouse where item_type=1 and shop_id=?) mw on mw.item_id=sins.id
            //     where sins.`status`=1 and sins.`use_status`=1";
            // if(isset($non_ids)){
            //     $non_ids[]=0;
            //     $sins_sql.=" and sins.id in (".implode(",",$non_ids).")";
            // }


            // $sql="select * from (
            //     ".$si_sql."
            //     UNION
            //     ".$sins_sql."
            //     ) temp ";
            $s_item=DB::select($si_sql." limit 5000",array($sc_user->shop_id,$sc_user->shop_id));
            // foreach($s_item as $_item){
            //     $sl=SupplyLocation::where('item_id',$_item->id)->where('shop_id',$sc_user->shop_id)->where('item_type',$_item->type)->first();
            //     $_item->location=isset($sl->location) ? $sl->location : "";
            // }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>sizeof($s_item),"item_info"=>$s_item));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "getSupply", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-03-09 10:59:55
     * @Description: 获取 领用未退库完 的 领用出库的 耗材批次
     */
    public function getSupplyReturn(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }

            $car_retrieval_code=Input::get("car_retrieval_code");
            $type=Input::get("type");
            $search_retrieval_code=Input::get("retrieval_code");
            $car_str=Input::get("car_str");
            if($type||$search_retrieval_code||$car_str){
                // $non_ids=SupplyItemNonStandard::retrievalCode($sc_user->shop_id,$car_retrieval_code,$type,$search_retrieval_code,$car_str);//获得非标的耗材id范围
                $si_ids=SupplyItem::retrievalCode($car_retrieval_code,$type,$search_retrieval_code,$car_str);//获得标准的耗材id范围
            }

            $si_sql="select si.id,'' car_model,si.car_model_comments,si.code,si.old_code,si.retrieval_code,si.type,supply_classification.id as scf_id,
                sb.brand_name item_brand_name,ss.name item_series_name,si.model item_model_name,'' item_specification,si.volume_size item_pack_unit,supply_unit.name item_sale_unit,si.name as item_name,
                supply_classification.name as scf_name 
                from supply_item si
                LEFT JOIN anhui_data.supply_unit  on supply_unit.id=si.sale_unit_id 
                left join supply_classification on supply_classification.id=si.supply_classification_id
                left join anhui_data.supply_series ss on ss.id=si.series_id
                left join anhui_data.supply_brand sb on sb.id=si.brand_id
                ";
            if(isset($si_ids)){
                $si_ids[]=0;
                $si_sql.=" where si.id in (".implode(",",$si_ids).")";
            }
            // $sins_sql="select sins.id,sins.car_model,sins.car_model as car_model_comments,sins.`code`,sins.`old_code`,sins.retrieval_code,1 type,statistical_classification.id as scf_id,
            //     sins.brand_name item_brand_name,sins.series_name item_series_name,sins.model item_model_name,sins.specification item_specification,sins.pack_unit item_pack_unit,sins.unit item_sale_unit,
            //     statistical_classification.name as scf_name  from supply_item_non_standard sins
            //     left join statistical_classification on statistical_classification.id=sins.st_classifi_id ";
            // if(isset($non_ids)){
            //     $non_ids[]=0;
            //     $sins_sql.=" where  sins.id in (".implode(",",$non_ids).")";
            // }

            $sql="select msi.* ,temp.car_model,temp.old_code,temp.car_model_comments,temp.item_brand_name,temp.item_series_name,temp.item_model_name,temp.item_specification,temp.item_pack_unit,temp.item_sale_unit,temp.scf_name as ss_name,temp.scf_id,temp.scf_name,temp.item_name 
                from maintenance_out_item msi
                left join maintenance_out_list mol on mol.id= msi.list_id
                join ( ".$si_sql.") temp on temp.id=msi.item_id
                where msi.shop_id=? and msi.status=1 and msi.number>msi.return_numer and mol.type=1";
            // if(Input::get("code")){//商品编码
            //     // $sql=$sql." and temp.code like '%".Input::get("code")."%'";
            //     $sql=$sql." and (temp.code like '%".Input::get("code")."%' or temp.old_code like '%".Input::get("code")."%')";
            // }
            // if(Input::get("retrieval_code")){//检索码
            //     $sql=$sql." and temp.retrieval_code like '%".Input::get("retrieval_code")."%'";
            // }
            $s_item=DB::select($sql,array($sc_user->shop_id));
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>sizeof($s_item),"item_info"=>$s_item));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "getSupplyReturn", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }



    /**
     * @Author:      lyt
     * @DateTime:    2016-02-29 18:02:09
     * @Description: 用于显示 用户 出库单的列表
     */
    public function outList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);
            $msl=MaintenanceOutList::leftJoin("sc_user",'sc_user.id','=','maintenance_out_list.cust_id')->
            leftJoin("maintenance_supplier",'maintenance_supplier.id','=','maintenance_out_list.consuming_id')->where("maintenance_out_list.shop_id",$sc_user->shop_id)->orderBy("maintenance_out_list.created_at",'desc');
            if(Input::get("type")!=""){
                $msl=$msl->where("maintenance_out_list.type",Input::get("type"));
            }
            if(Input::get("status")!=""){
                $msl=$msl->where("maintenance_out_list.status",Input::get("status"));
            }
            if(Input::get("date")!=""){
                $msl=$msl->where("maintenance_out_list.date",Input::get("date"));
            }
            if(Input::get("list_id")!=""){
                $msl=$msl->where("maintenance_out_list.id","like","%".Input::get("list_id")."%");
            }
            if(Input::get('implement_time')!=""){
                $it=Input::get('implement_time');
                $start_time=$it.' 00:00:00';
                $end_time=$it.' 23:59:59';
                $start_time=date("Y-m-d H:i:s",strtotime($start_time)-Config::get("config.report_time_diff"));
                $end_time=date("Y-m-d H:i:s",strtotime($end_time)-Config::get("config.report_time_diff"));
                $msl=$msl->whereBetween("maintenance_out_list.implement_time",array($start_time,$end_time));
            }
            $count=$msl->count();
            $msl=$msl->skip($page_size*($page-1))->take($page_size)->select("maintenance_out_list.id","maintenance_out_list.methed","maintenance_out_list.type","maintenance_out_list.consuming_id","maintenance_out_list.shop_type","maintenance_out_list.user_type","maintenance_out_list.date","maintenance_out_list.out_type","maintenance_out_list.status","maintenance_out_list.consuming_type","maintenance_out_list.desc","maintenance_out_list.implement_time","maintenance_supplier.name as suppliername","sc_user.real_name")->get();
            foreach ($msl as $_msl) {
                if($_msl->consuming_type==1){
                    if($_msl->methed==1){
                        $department=Department::find($_msl->consuming_id);
                        $_msl->shop_name=$department->name;
                    }elseif($_msl->methed==3){
                        if($_msl->shop_type==1){
                            if($_msl->user_type==1){
                                $sc=SCUser::find($_msl->consuming_id);
                                $_msl->shop_name=$sc->real_name;
                            }else{
                                $me=MaintenanceEngineers::find($_msl->consuming_id);
                                $_msl->shop_name=$me->name;
                            }
                        }else{
                            $department=Department::find($_msl->consuming_id);
                            $_msl->shop_name=$department->name;
                        }
                    }else{
                        $ms=MaintenanceShops::find($_msl->consuming_id);
                        $_msl->shop_name=$ms->name;
                    }
                }
                if($_msl->implement_time){
                    $_msl->implement_time=date("Y-m-d H:i:s",strtotime($_msl->implement_time)+Config::get("config.report_time_diff"));    
                }                
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"msl_info"=>$msl));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "storageList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

   /**
    * @Author:      lyt
    * @DateTime:    2016-03-04 13:24:43
    * @Description: 出库单的详情
    */
    public function out(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $class_one_info = array();
            $msl=MaintenanceOutList::leftJoin("sc_user",'sc_user.id','=','maintenance_out_list.cust_id')->
            leftJoin("maintenance_supplier",'maintenance_supplier.id','=','maintenance_out_list.consuming_id')
            ->where("maintenance_out_list.id",Input::get("id"))->where("maintenance_out_list.shop_id",$sc_user->shop_id)->select("maintenance_out_list.id","maintenance_out_list.consuming_id","maintenance_out_list.type","maintenance_out_list.shop_type","maintenance_out_list.user_type","maintenance_out_list.pay_type","maintenance_out_list.out_type","maintenance_out_list.methed","maintenance_out_list.return_type","maintenance_out_list.date","maintenance_out_list.implement_time","maintenance_out_list.status","maintenance_out_list.consuming_type","maintenance_out_list.desc","maintenance_supplier.name as suppliername","sc_user.real_name")->first();
            if($msl->consuming_type==1){
                if($msl->methed==1){
                    $department=Department::find($msl->consuming_id);
                    $msl->shop_name=$department->name;
                }elseif($msl->methed==3){
                    if($msl->shop_type==1){
                        if($msl->user_type==1){
                            $sc=SCUser::find($msl->consuming_id);
                            $msl->shop_name=$sc->real_name;
                        }else{
                            $me=MaintenanceEngineers::find($msl->consuming_id);
                            $msl->shop_name=$me->name;
                        }
                    }else{
                        $department=Department::find($msl->consuming_id);
                        $msl->shop_name=$department->name;
                    }
                }else{
                    $ms=MaintenanceShops::find($msl->consuming_id);
                    $msl->shop_name=$ms->name;
                }
            }
            if($msl){                
                $msi=MaintenanceOutItem::leftJoin("sc_user",'sc_user.id','=','maintenance_out_item.own_id')->
                // leftJoin("supply_subject",'supply_subject.id','=','maintenance_out_item.subject')->
                leftJoin("maintenance_datebase",'maintenance_datebase.id','=','maintenance_out_item.data_id')->
                where("maintenance_out_item.list_id",$msl->id)->where("maintenance_out_item.status","!=",2)->select("maintenance_out_item.*","sc_user.real_name","maintenance_datebase.name as data_name")->get();
                $msl->implement_time=isset($msl->implement_time)?date("Y-m-d H:i:s",strtotime($msl->implement_time)+Config::get("config.report_time_diff")):"";
                foreach ($msi as $_msi) {
                    $_msi->implement_time=isset($_msi->implement_time)?date("Y-m-d H:i:s",strtotime($_msi->implement_time)+Config::get("config.report_time_diff")):"";
                    // if($_msi->item_type==0){//如果是标准耗材
                    $item_info=SupplyItem::getCacheItemInfo($_msi->item_id);
                    $_msi->subject_name=isset($item_info)?$item_info->scf_name:"";
                    $_msi->scf_name=isset($item_info)?$item_info->scf_name:"";
                    $scf=SupplyClassification::getClassification($item_info->st_classifi_id);
                    $_msi->two_id=$scf->two_id;
                    $_msi->two=$scf->two;
                    $_msi->one_id=$scf->one_id;
                    $_msi->one=$scf->one;
                    $_msi->brand_name=$item_info->brand_name;
                    $_msi->goods_name=$item_info->name;
                    $_msi->car_model_comments=$item_info->car_model_comments;
                    $_msi->item_name=$item_info->name;
                    // }else{
                    //     $item_info=SupplyItemNonStandard::getCacheItemInfo($_msi->item_id);
                    //     $scf=StatisticalClassification::getClassification($item_info->st_classifi_id);
                    //     $_msi->scf_name=isset($item_info)?$item_info->scf_name:"";
                    //     $_msi->two_id=$scf->two_id;
                    //     $_msi->two=$scf->two;
                    //     $_msi->one_id=$scf->one_id;
                    //     $_msi->one=$scf->one;
                    //     $_msi->use_status=$item_info->use_status;
                    //     $_msi->brand_name=$item_info->brand_name;
                    //     $_msi->car_model=$item_info->car_model;
                    //     $_msi->goods_name=$item_info->scf_name.$item_info->series_name.$item_info->model.$item_info->specification;
                    // }

                    if(!isset($class_one_info[$_msi->one_id])){ //如果没有一类ID，创建。如果有则相加
                        $class_one_info[$_msi->one_id]['one_id'] = $_msi->one_id;
                        $class_one_info[$_msi->one_id]['name'] = $scf->one;
                        $class_one_info[$_msi->one_id]['number'] = $_msi->number;
                        $class_one_info[$_msi->one_id]['tax_purchase_subtotal'] = bcdiv($_msi->tax_purchase_subtotal,100,6);
                    } else {
                        $class_one_info[$_msi->one_id]['number'] += $_msi->number;
                        $class_one_info[$_msi->one_id]['tax_purchase_subtotal'] += bcdiv($_msi->tax_purchase_subtotal,100,6);
                    }
                }
                $msl->item=$msi;
                $msl->class_one_info = array_values($class_one_info);
            }else{
                $response = Lang::get("scs_error.maintenance_out_notexit_60002");
                break;
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("mol_info"=>$msl));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "storageList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }



     /**
     * @Author:      lyt
     * @DateTime:    2016-02-26 17:36:11
     * @Description: 获取能出库的耗材批次
     */
    public function getSupplyStorage(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }

            $car_retrieval_code=Input::get("car_retrieval_code");
            $type=Input::get("type");
            $search_retrieval_code=Input::get("retrieval_code");

            $car_str=Input::get("car_str");
            if($type||$search_retrieval_code||$car_str){
                // $non_ids=SupplyItemNonStandard::retrievalCode($sc_user->shop_id,$car_retrieval_code,$type,$search_retrieval_code,$car_str);//获得非标的耗材id范围
                $si_ids=SupplyItem::retrievalCode($car_retrieval_code,$type,$search_retrieval_code,$car_str);//获得标准的耗材id范围
            }

            $si_sql="select si.id,si.car_model_comments as car_model,si.car_model_comments,si.code,si.old_code,si.retrieval_code,sb.brand_name item_brand_name,ss.name item_series_name,si.model item_model_name,'' item_specification,si.volume_size item_pack_unit,sus.name item_sale_unit,su.name as unit,si.type,si.name as item_name, supply_classification.id as scf_id,
                supply_classification.name as scf_name 
                from supply_item si
                LEFT JOIN anhui_data.supply_unit sus  on sus.id=si.sale_unit_id 
                LEFT JOIN anhui_data.supply_unit su on su.id=si.unit_id 
                left join anhui_data.supply_series ss on ss.id=si.series_id
                left join anhui_data.supply_brand sb on sb.id=si.brand_id
                left join supply_classification on supply_classification.id=si.supply_classification_id";
            if(isset($si_ids)){
                $si_ids[]=0;
                $si_sql.=" where si.id in (".implode(",",$si_ids).")";
            }
            // $sins_sql="select sins.id,sins.car_model,sins.car_model as car_model_comments,sins.`code`,sins.`old_code`,sins.retrieval_code,sins.brand_name item_brand_name,sins.series_name item_series_name,sins.model item_model_name,sins.specification item_specification,sins.pack_unit item_pack_unit,sins.unit item_sale_unit,sins.unit,1 type,statistical_classification.id as scf_id,
            //     statistical_classification.name as scf_name  from supply_item_non_standard sins
            //     left join statistical_classification on statistical_classification.id=sins.st_classifi_id ";
            // if(isset($non_ids)){
            //     $non_ids[]=0;
            //     $sins_sql.=" where  sins.id in (".implode(",",$non_ids).")";
            // }

            $sql="select msi.* ,temp.car_model,temp.car_model_comments,temp.old_code,temp.item_brand_name,temp.item_series_name,temp.item_model_name,temp.item_specification,temp.item_pack_unit,temp.item_sale_unit, md.name  data_name ,temp.scf_name as ss_name,temp.scf_id,temp.scf_name ,temp.item_name 
                from maintenance_storage_item msi
                LEFT JOIN maintenance_datebase md on msi.data_id=md.id
                JOIN ( ".$si_sql." ) temp on  temp.id=msi.item_id
                where msi.shop_id=? and msi.status=1 and msi.type=1 and msi.current_number>0 ";
            // if(Input::get("code")){//商品编码
            //     $sql=$sql." and (temp.code like '%".Input::get("code")."%' or temp.old_code like '%".Input::get("code")."%')";
            //     // $sql=$sql." and temp.code like '%".Input::get("code")."%'";
            // }
            // if(Input::get("retrieval_code")){//检索码
            //     $sql=$sql." and temp.retrieval_code like '%".Input::get("retrieval_code")."%'";
            // }
            $s_item=DB::select($sql,array($sc_user->shop_id));
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>sizeof($s_item),"item_info"=>$s_item));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "getSupplyStorage", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);

    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-03-02 16:00:11
     * @Description: 获取待处理的 订单出库请求
     */
    public function getShopOrderOut(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            // $ss=SupplySubject::all();
            // $subject_arr=array();
            // foreach ($ss as $_ss) {
            //     $subject_arr[$_ss->id]=$_ss->name;
            // }
            // print_r($subject_arr);
            // exit;
            $s_item=MaintenanceOutOrder::where('shop_id',$sc_user->shop_id)->where('status',0)->get();
            $finally_arr=array();
            foreach ($s_item as $item) {
                // if($item->type==0){
                $mw=MaintenanceWarehouse::where('shop_id',$sc_user->shop_id)->where('item_id',$item->item_id)->first();
                $si_info=SupplyItem::getCacheItemInfo($item->item_id);
                $code=$si_info->code;
                $old_code=$si_info->old_code;
                $subject=$si_info->subject_name;
                $brand_name=$si_info->brand_name;
                $name=$si_info->name;
                $model=$si_info->model;
                $scf_id=$si_info->st_classifi_id;
                $scf_name=$si_info->scf_name;
                $series_name=$si_info->series_name;
                $specification=$si_info->specification;
                $pack_unit=$si_info->pack;
                $sale_unit=$si_info->sale_unit;
                // }else{
                //     $mw=MaintenanceWarehouse::where('shop_id',$sc_user->shop_id)->where('item_id',$item->item_id)->where('item_type',1)->first();
                //     $sins_info=SupplyItemNonStandard::getCacheItemInfo($item->item_id);
                //     $code=$sins_info->code;
                //     $old_code=$sins_info->old_code;
                //     $subject="";
                //     $brand_name=$sins_info->brand_name;
                //     $name=$sins_info->name;
                //     $model=$sins_info->model;
                //     $scf_id=$sins_info->st_classifi_id;
                //     $scf_name=$sins_info->scf_name;
                //     $series_name=$sins_info->series_name;
                //     $specification=$sins_info->specification;
                //     $pack_unit=$sins_info->pack_unit;
                //     $sale_unit=$sins_info->unit;
                // }

                // $code=$item->type==0?$item->si_model:$item->code;
                // $old_code=$item->type==0?$item->si_model:$item->old_code;
                // $subject=$item->type==0?$subject_arr[$item->si_subject]:$subject_arr[$item->subject];

                // $brand_name=$item->type==0?$item->si_brand_name:$item->brand_name;
                // $name=$item->type==0?$item->si_brand_name.' '.$item->si_series_name.' '.$item->si_model:$item->name;
                // $model=$item->type==0?$item->si_model:$item->model;
                $number=isset($mw->number)?$mw->number:0;
                $finally_arr[]=array(
                    "id"=>$item->id,
                    "order_id"=>$item->order_id,
                    "code"=>$code,
                    "old_code"=>$old_code,
                    "subject"=>$subject,
                    "brand_name"=>$brand_name,
                    "name"=>$name,
                    "model"=>$model,
                    "number"=>$item->number,
                    "data_number"=>$number,
                    "item_id"=>$item->item_id,
                    "item_type"=>$item->type,
                    "scf_id"=>$scf_id,
                    "scf_name"=>$scf_name,
                    "item_brand_name"=>$brand_name,
                    "item_series_name"=>$series_name,
                    "item_model_name"=>$model,
                    "item_specification"=>$specification,
                    "item_pack_unit"=>$pack_unit,
                    "item_sale_unit"=>$sale_unit,
                    "item_name"=>$si_info->name,
                );
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>sizeof($finally_arr),"item_info"=>$finally_arr));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "getShopOrderOut", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }



    /**
     * @Author:      lyt
     * @DateTime:    2016-03-04 15:56:38
     * @Description: 获取待处理的 订单退库请求
     */
    public function getShopOrderReturn(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            // $ss=SupplySubject::all();
            // $subject_arr=array();
            // foreach ($ss as $_ss) {
            //     $subject_arr[$_ss->id]=$_ss->name;
            // }
            $sql="SELECT
                    moo.*, mw.number data_number
                    -- si.model si_model,
                    -- si.subject si_subject,
                    -- sb.brand_name si_brand_name,
                    -- ss.`name`  si_series_name,
                    -- sion.`code`,
                    -- sion.old_code,
                    -- sion.brand_name,
                    -- sion.series_name,
                    -- sion.`name`,
                    -- sion.model,
                    -- sion.subject,
                    -- sion.specification
                FROM
                    maintenance_return_order moo
                -- LEFT JOIN supply_item si ON moo.item_id = si.id
                -- LEFT JOIN supply_series ss ON ss.id = si.series_id
                -- LEFT JOIN supply_brand sb ON sb.id = si.brand_id
                -- LEFT JOIN supply_item_non_standard sion ON sion.id = moo.item_id
                LEFT JOIN maintenance_warehouse mw ON mw.item_id = moo.item_id
                WHERE
                    moo.shop_id = ?
                AND mw.shop_id = ?
                AND moo.`status` = 0";
            $s_item=DB::select($sql,array($sc_user->shop_id,$sc_user->shop_id));
            $finally_arr=array();
            foreach ($s_item as $item) {
                // if($item->type==0){
                    $si_info=SupplyItem::getCacheItemInfo($item->item_id);
                    $code=$si_info->code;
                    $old_code=$si_info->old_code;
                    $subject=$si_info->subject_name;
                    $brand_name=$si_info->brand_name;
                    $name=$si_info->name;
                    $model=$si_info->model;
                    $scf_id=$si_info->st_classifi_id;
                    $scf_name=$si_info->scf_name;
                    $series_name=$si_info->series_name;
                    $specification=$si_info->specification;
                    $pack_unit=$si_info->pack;
                    $sale_unit=$si_info->sale_unit;
                // }else{
                //     $sins_info=SupplyItemNonStandard::getCacheItemInfo($item->item_id);
                //     $code=$sins_info->code;
                //     $old_code=$sins_info->old_code;
                //     $subject="";
                //     $brand_name=$sins_info->brand_name;
                //     $name=$sins_info->name;
                //     $model=$sins_info->model;
                //     $scf_id=$sins_info->st_classifi_id;
                //     $scf_name=$sins_info->scf_name;
                //     $series_name=$sins_info->series_name;
                //     $specification=$sins_info->specification;
                //     $pack_unit=$sins_info->pack_unit;
                //     $sale_unit=$sins_info->uint;
                // }

                $finally_arr[]=array(
                    "id"=>$item->id,
                    "order_id"=>$item->order_id,
                    "code"=>$code,
                    "old_code"=>$old_code,
                    "subject"=>$subject,
                    "brand_name"=>$brand_name,
                    "name"=>$name,
                    "model"=>$model,
                    "number"=>$item->number,
                    "data_number"=>$item->data_number,
                    "item_id"=>$item->item_id,
                    "item_type"=>$item->type,
                    "scf_id"=>$scf_id,
                    "scf_name"=>$scf_name,
                    "item_brand_name"=>$brand_name,
                    "item_series_name"=>$series_name,
                    "item_model_name"=>$model,
                    "item_specification"=>$specification,
                    "item_pack_unit"=>$pack_unit,
                    "item_sale_unit"=>$sale_unit
                );
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>sizeof($finally_arr),"item_info"=>$finally_arr));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "getShopOrderOut", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:    2016-03-07 16:53:43
     * @Description: 库存的查询
     */
    //
    public function inventoryDetai(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }

            $car_retrieval_code=Input::get("car_retrieval_code");
            $type=Input::get("type");
            $search_retrieval_code=Input::get("retrieval_code");
            $car_str=Input::get("car_str");
            if($type||$search_retrieval_code||$car_str){
                // $non_ids=SupplyItemNonStandard::retrievalCode($sc_user->shop_id,$car_retrieval_code,$type,$search_retrieval_code,$car_str);//获得非标的耗材id范围
                $si_ids=SupplyItem::retrievalCode($car_retrieval_code,$type,$search_retrieval_code,$car_str);//获得标准的耗材id范围
            }

            $si_sql="select si.id,'' car_model,si.code,si.old_code,si.retrieval_code,sb.brand_name item_brand_name,ss.name item_series_name,si.model item_model_name,'' item_specification,si.volume_size item_pack_unit,sus.name item_sale_unit,su.name unit,si.car_model_comments,si.type, supply_classification.id as scf_id,
                supply_classification.name as scf_name ,si.name as item_name
                from supply_item si
                LEFT JOIN anhui_data.supply_unit sus  on sus.id=si.sale_unit_id 
                LEFT JOIN anhui_data.supply_unit su on su.id=si.unit_id 
                left join anhui_data.supply_series ss on ss.id=si.series_id
                left join anhui_data.supply_brand sb on sb.id=si.brand_id
                left join supply_classification on supply_classification.id=si.supply_classification_id where 1=1 ";
            if(isset($si_ids)){
                $si_ids[]=0;
                $si_sql.=" and si.id in (".implode(",",$si_ids).")";
            }
            if(Input::get("old_code")){//商品编码
                $si_sql=$si_sql." and old_code like '%".Input::get("old_code")."%'";
            }
            // $sins_sql="select sins.id,sins.car_model,sins.`code`,sins.`old_code`,sins.retrieval_code,sins.brand_name item_brand_name,sins.series_name item_series_name,sins.model item_model_name,sins.specification item_specification,sins.pack_unit item_pack_unit,sins.unit item_sale_unit,sins.unit,sins.car_model as car_model_comments,1 type,statistical_classification.id as scf_id,
            //     statistical_classification.name as scf_name  from supply_item_non_standard sins
            //     left join statistical_classification on statistical_classification.id=sins.st_classifi_id where 1=1 ";
            // if(isset($non_ids)){
            //     $non_ids[]=0;
            //     $sins_sql.=" and  sins.id in (".implode(",",$non_ids).")";
            // }
            //  if(Input::get("old_code")){//商品编码
            //     $sins_sql=$sins_sql." and old_code like '%".Input::get("old_code")."%'";
            // }


            // if(Input::get("car_brand_id")||Input::get("car_series_id")||Input::get("car_model_id")){
            //     $temp_sql="select si.id,si.model code,si.model old_code,si.model retrieval_code,si.model,ss.unit,0 type from supply_item si
            //         left join supply_series ss on ss.id=si.series_id
            //         LEFT JOIN supply_product_item spi on spi.supply_item_id=si.id
            //         where si.`status`=1";
            //     if(Input::get("car_brand_id")){
            //         $temp_sql=$temp_sql." and spi.car_brand_id= ".Input::get("car_brand_id");
            //     }
            //     if(Input::get("car_series_id")){
            //         $temp_sql=$temp_sql." and spi.car_series_id= ".Input::get("car_series_id");
            //     }
            //     if(Input::get("car_model_id")){
            //         $temp_sql=$temp_sql." and spi.car_model_id= ".Input::get("car_model_id");
            //     }
            // }else{
            //     $temp_sql="select si.id,si.model code,si.model old_code,si.model retrieval_code,si.model,ss.unit,0 type from supply_item si
            //         left join supply_series ss on ss.id=si.series_id
            //         where si.`status`=1";
            // }
            $sql="select msi.* ,temp.item_brand_name,temp.old_code,temp.car_model,temp.item_series_name,temp.item_model_name,temp.item_specification,temp.item_pack_unit,temp.item_sale_unit, md.name  data_name ,temp.scf_name as ss_name,ms.name suppliername,temp.unit,temp.id temp_id,temp.type temp_type,temp.item_name,temp.scf_id,temp.scf_name,temp.car_model_comments 
                from maintenance_storage_item msi
                LEFT JOIN maintenance_storage_list msl on msl.id=msi.list_id
                LEFT JOIN maintenance_supplier ms on ms.id=msl.supplier
                LEFT JOIN maintenance_datebase md on msi.data_id=md.id
                join ( ".$si_sql.") temp on temp.id=msi.item_id 
                where msi.shop_id=? and msi.status=1 and msi.type=1 and msi.current_number>0 ";
            if(Input::get("storage_id")){//批次
                $sql=$sql." and msi.list_id='".Input::get("storage_id")."'";
            }           
            if(Input::get("location")){//批次
                $sql=$sql." and msi.location = '".Input::get("location")."'";
            }
            // print_r($sql);exit;
            $s_item=DB::select($sql,array($sc_user->shop_id));
            $finally_arr=array();
            $b_temp_arr=array();
            $fb_temp_arr=array();
            foreach ($s_item as $item) {
                $finally_arr[]=array(
                    "suppliername"=>$item->suppliername,
                    "date_name"=>$item->data_name,
                    "list_id"=>$item->list_id,
                    "code"=>$item->code,
                    "old_code"=>$item->old_code,
                    "car_model"=>$item->car_model,
                    "name"=>$item->name,
                    "model"=>$item->model,
                    "unit"=>$item->item_sale_unit,//暂时先用这个单位
                    "number"=>$item->number,
                    "current_number"=>$item->current_number,
                    "subject_name"=>$item->ss_name,
                    "scf_id"=>$item->scf_id,
                    "scf_name"=>$item->scf_name,
                    "location"=>$item->location,
                    "tax_purchase_price"=>$item->tax_purchase_price,
                    "tax_purchase_subtotal"=>$item->tax_purchase_subtotal,
                    "item_brand_name"=>$item->item_brand_name,
                    "item_series_name"=>$item->item_series_name,
                    "item_model_name"=>$item->item_model_name,
                    "item_specification"=>$item->item_specification,
                    "item_pack_unit"=>$item->item_pack_unit,
                    "item_sale_unit"=>$item->item_sale_unit,
                    "car_model_comments"=>$item->car_model_comments,
                    "item_name"=>$item->item_name,
                );
                // if($item->temp_type==0){//说明标准耗材
                    if(isset($b_temp_arr[$item->temp_id])){
                        $b_temp_arr[$item->temp_id]["number"]=$b_temp_arr[$item->temp_id]["number"]+$item->current_number;
                    }else{
                        $b_temp_arr[$item->temp_id]=array(
                            "old_code"=>$item->old_code,
                            "car_model"=>'',
                            "code"=>$item->code,
                            "name"=>$item->name,
                            "model"=>$item->model,
                            "unit"=>$item->item_sale_unit,
                            "number"=>$item->current_number,
                            "subject_name"=>$item->ss_name,
                            "scf_id"=>$item->scf_id,
                            "scf_name"=>$item->scf_name,
                            "item_brand_name"=>$item->item_brand_name,
                            "item_series_name"=>$item->item_series_name,
                            "item_model_name"=>$item->item_model_name,
                            "item_specification"=>$item->item_specification,
                            "item_pack_unit"=>$item->item_pack_unit,
                            "item_sale_unit"=>$item->item_sale_unit,
                            "car_model_comments"=>$item->car_model_comments,
                            "item_name"=>$item->item_name,
                        );
                    }
                // }else{
                //     if(isset($fb_temp_arr[$item->temp_id])){
                //         $fb_temp_arr[$item->temp_id]["number"]=$fb_temp_arr[$item->temp_id]["number"]+$item->current_number;
                //     }else{
                //         $fb_temp_arr[$item->temp_id]=array(
                //             "old_code"=>$item->old_code,
                //             "car_model"=>$item->car_model,
                //             "code"=>$item->code,
                //             "name"=>$item->name,
                //             "model"=>$item->model,
                //             "unit"=>$item->unit,
                //             "number"=>$item->current_number,
                //             "subject_name"=>$item->ss_name,
                //             "scf_id"=>$item->scf_id,
                //             "scf_name"=>$item->scf_name,
                //             "item_brand_name"=>$item->item_brand_name,
                //             "item_series_name"=>$item->item_series_name,
                //             "item_model_name"=>$item->item_model_name,
                //             "item_specification"=>$item->item_specification,
                //             "item_pack_unit"=>$item->item_pack_unit,
                //             "item_sale_unit"=>$item->item_sale_unit,
                //             "car_model_comments"=>$item->car_model_comments,
                //         );
                //     }
                // }
            }
            $total_arr=array();
            foreach ($b_temp_arr as $_bta) {
                $total_arr[]=$_bta;
            }
            // foreach ($fb_temp_arr as $_fbta) {
            //     $total_arr[]=$_fbta;
            // }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("item_info"=>$finally_arr,"total_info"=>$total_arr));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "inventoryDetai", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:    2016-05-19 14:33:26
     * @Description: 根据耗材 类型和耗材型号获取 能出库入库信息
     */
    public function getMsiList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                // 'item_type' => 'required',
                'item_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $msi=MaintenanceStorageItem::where("shop_id",$sc_user->shop_id)
                ->where("status",1)
                ->where("type",1)
                // ->where("item_type",Input::get("item_type"))
                ->where("item_id",Input::get("item_id"))
                ->where("current_number",">",0)
                ->select('id',"list_id","tax_purchase_price","number","current_number")->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>sizeof($msi),"item_info"=>$msi));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "getMsiList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-05-23 15:26:18
     * @Description: 配件查询
     * @param int $current_number 库存数量状态  [1:库存大于0;2:全部; 默认值为2]
     * @param int $number_sort 库存排序  [1:正序;2:倒序;]
     * @link http://api.anhui.com/v1/scs/stock/inventoryDetaiNew?token=efc85ce01d0e523e5d4507fac1beb4f6&retrieval_code=油&current_number=1
     */
    public function inventoryDetaiNew(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);
            $car_retrieval_code=Input::get("car_retrieval_code");
            $type=Input::get("type");
            $search_retrieval_code=Input::get("retrieval_code");
            $current_number = Input::get('current_number', 2);  //库存数量状态  [1:库存大于0;2:全部; 默认值为2]
            $number_sort = Input::get('number_sort', 0);        //库存排序  [1:正序;2:倒序;]

            $car_str=Input::get("car_str");
            if($type||$search_retrieval_code||$car_str){
                // $non_ids=SupplyItemNonStandard::retrievalCode($sc_user->shop_id,$car_retrieval_code,$type,$search_retrieval_code,$car_str);//获得非标的耗材id范围
                $si_ids=SupplyItem::retrievalCode($car_retrieval_code,$type,$search_retrieval_code,$car_str);//获得标准的耗材id范围
            }

            $si_sql="select si.id,si.type,mw.id mw_id,mw.number,si.code,si.supply_classification_id 
                from supply_item si
                LEFT JOIN (select * from maintenance_warehouse where shop_id=?) mw on mw.item_id=si.id
                where ((si.`status`=1 and si.type=0 ) or (si.type=1 and si.shop_id=?) or mw.id is not null )";
            if(isset($si_ids)){
                $si_ids[]=0;
                $si_sql.=" and si.id in (".implode(",",$si_ids).")";
            }
            if($current_number == 1){
                $si_sql.=" and mw.number > 0";
            }
            // $sins_sql="select sins.id,1 type,mw.id mw_id,mw.number ,sins.code,sins.st_classifi_id 
            //     from supply_item_non_standard sins
            //     LEFT JOIN (select * from maintenance_warehouse where item_type=1 and shop_id=?) mw on mw.item_id=sins.id
            //     where sins.`status`=1";
            // if(isset($non_ids)){
            //     $non_ids[]=0;
            //     $sins_sql.=" and sins.id in (".implode(",",$non_ids).")";
            // }

            $sql="select count(1) count from (
                ".$si_sql."
                ) temp where 1=1 ";
            $sql2="select * from (
                ".$si_sql."
                ) temp where 1=1 ";
            if(Input::get("st_classifi_id")){
                $sql=$sql.' and temp.supply_classification_id='.Input::get("st_classifi_id");
                $sql2=$sql2.' and temp.supply_classification_id='.Input::get("st_classifi_id");
            }
            if(Input::get("code")){
                $sql=$sql.' and temp.code like "%'.Input::get("code").'%"';
                $sql2=$sql2.' and temp.code like "%'.Input::get("code").'%"';
            }

            $count=DB::select($sql,array($sc_user->shop_id,$sc_user->shop_id));
            
            //$sql2= $sql2." limit ?,? ";
            //排序
            if($number_sort == 1){
                $sql2 = $sql2.' order by temp.number limit ?,?';
            }elseif ($number_sort == 2) {
                $sql2 = $sql2.' order by temp.number desc limit ?,?';
            }else{
                $sql2= $sql2." limit ?,? ";
            }
            $s_item=DB::select($sql2,array($sc_user->shop_id,$sc_user->shop_id,$page_size*($page-1),$page_size));

            foreach ($s_item as $_mis) {
                // if($_mis->type==0){//说明是标准耗材
                    $si_info=SupplyItem::getCacheItemInfo($_mis->id);
                    $_mis->code=$si_info->code;
                    $_mis->old_code=$si_info->old_code;
                    $_mis->brand_name=$si_info->brand_name;
                    $_mis->series_name=$si_info->series_name;
                    $_mis->model=$si_info->model;
                    $_mis->specification=$si_info->specification;
                    $_mis->scf_id=$si_info->st_classifi_id;
                    $_mis->scf_name=$si_info->scf_name;
                    $_mis->unit=$si_info->unit;
                    $_mis->car_model='';
                    $_mis->car_model_comments=$si_info->car_model_comments;  
                    $_mis->item_name=$si_info->name;                  
                // }else{
                //     $sins_info=SupplyItemNonStandard::getCacheItemInfo($_mis->id);
                //     $_mis->code=$sins_info->code;
                //     $_mis->old_code=$sins_info->old_code;
                //     $_mis->brand_name=$sins_info->brand_name;
                //     $_mis->series_name=$sins_info->series_name;
                //     $_mis->model=$sins_info->model;
                //     $_mis->specification=$sins_info->specification;
                //     $_mis->scf_id=$sins_info->st_classifi_id;
                //     $_mis->scf_name=$sins_info->scf_name;
                //     $_mis->unit=$sins_info->unit;
                //     $_mis->car_model=$sins_info->car_model;
                //     $_mis->car_model_comments=$sins_info->car_model;
                // }
                $sl=SupplyLocation::where('item_id',$_mis->id)->where('shop_id',$sc_user->shop_id)->first();
                $_mis->location=isset($sl->location) ? $sl->location : "";
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count[0]->count,"item_info"=>$s_item));
        }while(false);
        // Log::info("info", array("system" => "scs" ,"event" => "inventoryDetaiNew", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-05-23 18:51:15
     * @Description: 耗材的 历史入库批次显示
     */
    public function supplyShow(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'item_id' => 'required',
                // 'item_type' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);
            $msi=MaintenanceStorageItem::where("shop_id",$sc_user->shop_id)->where("status",1)->where("type",1)->where("item_id",Input::get("item_id"))->orderBy('created_at','desc');
            $current_number=Input::get("current_number");
            if(isset($current_number)&&$current_number){
               $msi=$msi->where("current_number",">",$current_number); 
            }
            $count=$msi->count();
            $msi=$msi->skip($page_size*($page-1))->take($page_size)->select("id","list_id","tax_purchase_price","number","location","current_number")->get();
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"item_info"=>$msi));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "supplyShow", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-05-24 10:35:57
     * @Description: 耗材的 最近10次售卖记录 信息
     */
    public function supplySale(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'item_id' => 'required',
                // 'item_type' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);
            $moo=MaintenanceOutOrder::where("maintenance_out_order.shop_id",$sc_user->shop_id)
                ->leftJoin('orders','orders.order_id','=','maintenance_out_order.order_id')
                ->whereNotIn('orders.status', array(1010,1110,1210,1310,1410))
                ->whereIn('orders.status',array(1117,1217,1417,1018))
                // ->where("maintenance_out_order.type",Input::get("item_type"))
                ->where("maintenance_out_order.item_id",Input::get("item_id"))
                ->where("maintenance_out_order.status",2)
                ->orderBy("maintenance_out_order.created_at","desc")
                ->select("maintenance_out_order.order_id","maintenance_out_order.id","maintenance_out_order.created_at","number","return_number","product_item_id","product_type","car_no");
            $count=$moo->count();
            
            $moo=$moo->skip($page_size*($page-1))->take($page_size)->get();
            foreach ($moo as $_moo) {

                $orders=Orders::find($_moo->order_id);
                $sale_amount=0;
                $discount=1;
                switch ($_moo->product_type) {
                    case 'enterprise':
                        $opei=OrderProductEsItem::find($_moo->product_item_id);
                        $sale_amount=$opei->amount;
                        break;
                    case 'activity':
                        $opaci=OrderProductAcItem::find($_moo->product_item_id);
                        $sale_amount=$opaci->amount;
                        break;
                    case 'promotion':
                            $opi=OrderProductItem::find($_moo->product_item_id);
                            $sale_amount=$opi->amount;
                        break;
                    case 'base':
                            $opbi=OrderProductBaseItem::find($_moo->product_item_id);
                            $sale_amount=$opbi->amount;
                            $discount=$opbi->discount;
                        break;
                    case 'non_standard':
                            $opns=OrderProductNonStandard::where('id',$_moo->product_item_id)->where('status',1)->first();
                            $sale_amount=$opns->amount;
                            $discount=$opns->discount;
                        break;
                }
                $tax_purchase_price=MaintenanceOutItem::where('order_out_id',$_moo->id)->where('item_id',Input::get('item_id'))->where('status',1)->max('tax_purchase_price');
                $_moo->tax_purchase_price=$tax_purchase_price;
                $_moo->amount=$sale_amount;
                $_moo->discount=$discount;
                $_moo->car_brand_id=$orders->car_brand_id;
                $_moo->car_brand_name=$orders->car_brand_name;
                $_moo->car_series_id=$orders->car_series_id;
                $_moo->car_series_name=$orders->car_series_name;
                $_moo->car_model_id=$orders->car_model_id;
                $_moo->car_model_name=$orders->car_model_name;
            }            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"moo_info"=>$moo));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "supplySale", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:                zk
     * @DateTime:              18-3-28 上午11:50
     * @Description:           直营店 耗材库存信息
     * @param string $token     用户token
     * @param int $item_id      耗材id
     * @link http://api.anhui.com/v1/scs/stock/supplyInventory?token=1c384c684bee02f6e1fb41b0f9fe9df1&item_id=2085976
     */
    public function supplyInventory(){
        $validator = Validator::make(Input::all(), [
            'token' => 'required',
            'item_id' => 'required',
        ]);
        $response = [
            'code' => 0,
            'msg' => 'ok',
        ];
        
        do{
            if($validator->fails()){
                $response = Lang::get('scs_error.station_args_error_31001');
                $response['result'] = $validator->messages()->all();
                break;
            }
            $sc_user = $this->verificationSCSUserToken(Input::get('token'), $response);
            if(is_null($sc_user)){
                $response = Lang::get('scs_error.station_token_not_exist_31002');
                break;
            }
            $item_id = Input::get('item_id');
            $list = MaintenanceStorageItem::leftJoin('maintenance_shops AS shop', 'maintenance_storage_item.shop_id', '=', 'shop.id')
                    ->select(DB::raw('maintenance_storage_item.id, maintenance_storage_item.data_id, maintenance_storage_item.shop_id, sum(maintenance_storage_item.current_number) as current_number, shop.name as shop_name'))
                    ->where('maintenance_storage_item.item_id', $item_id)
                    ->where('maintenance_storage_item.type', 1)
                    ->where('maintenance_storage_item.status', 1)
                    ->where('shop.status', 1)
                    ->groupBy('maintenance_storage_item.shop_id')
                    ->groupBy('maintenance_storage_item.data_id')
                    ->get();        
            $new_list = [];
            $count = ['total' => 0, 'peiJian_total' => 0, 'fuLiao_total' => 0];
            if(!empty($list)){
                foreach ($list as $v) {
                    $database = MainDateBase::find($v->data_id);    //门店仓库类型
                    $v->name = $database->name;
                    $v->type = $database->type;
                    
                    if (!isset($new_list[$v->shop_id]['detail'])) { //配件库、辅料库 初期化
                        $new_list[$v->shop_id]['detail'][0] = ['type' => 0, 'current_number' => 0];     //配件库
                        $new_list[$v->shop_id]['detail'][1] = ['type' => 1, 'current_number' => 0];     //辅料库
                    }
                    
//                    $new_list[$v->shop_id]['detail'][$v->type] = $v;
                    $new_list[$v->shop_id]['detail'][$v->type]['type'] = $v->type;
                    $new_list[$v->shop_id]['detail'][$v->type]['current_number'] = $v->current_number;
//                    $new_list[$v->shop_id]['detail'][$v->type]['name'] = $v->name;
                    $new_list[$v->shop_id]['shop_id'] = $v->shop_id;
                    $new_list[$v->shop_id]['shop_name'] = $v->shop_name;
                    if (isset($new_list[$v->shop_id]['current_number'])) {
                        $new_list[$v->shop_id]['current_number'] += $v->current_number;
                    }else {
                        $new_list[$v->shop_id]['current_number'] = $v->current_number;
                    }
                    
                    //计算所有的总数
                    $count['total'] += $v['current_number'];
                    if($v['type'] == 0){
                        $count['peiJian_total'] += $v['current_number'];
                    }
                    if($v['type'] == 1){
                        $count['fuLiao_total'] += $v['current_number'];
                    }
                }
//需要的时候 以下可以再放开……              
//                foreach ($new_list as $k=>$v) { //聚合完成后。如果辅料库，和配件库都是0 就不显示了
//                    if($v["current_number"] == 0){
//                        unset($new_list[$k]);
//                    }
//                }
//                $new_list = array_values($new_list);
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ['list' => $new_list, 'count' => $count]);
            
        } while (FALSE);
        Log::info('info', array('system' => 'scs' ,'event' => 'supplyInventory', 'input' =>Input::all() ,'output' => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-09-14 16:27:51
     * @Description: 滞销查询
     */
    public function unsalable_inquiry_detail(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'begen_time' => 'required',
                'end_time' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $begen_time=Input::get("begen_time");
            $end_time=Input::get("end_time");
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);

            //查出结束时间期末 存在库存的耗材
            $mwos=MaintenanceWarehouseOrderStock::where("shop_id",$sc_user->shop_id)->where("date",$end_time)->where("number",">",0)->get();
            // $mwos=MaintenanceWarehouse::where("shop_id",$sc_user->shop_id)->where("number",">",0)->get();
            $key_ids=$key_value=array();
            foreach ($mwos as $_mwos) {
                // $k=$_mwos->item_type.'-'.$_mwos->item_id;
                $k=$_mwos->item_id;
                $key_ids[]=$k;
                // $key_value[$k]=$_mwos;
            }
            //查找时间段内有过销售 记录的耗材信息
            $sf_id=DB::select("SELECT moi.item_id,moi.item_type
                FROM maintenance_out_list mol
                JOIN maintenance_out_item moi ON mol.id = moi.list_id
                WHERE
                 mol.shop_id=?
                and mol.type =1 
                AND mol.methed= 3
                AND mol.`status` = 1
                AND moi.`status` = 1
                and mol.implement_time>? and mol.implement_time<=?                
                group by moi.item_id ",array($sc_user->shop_id,$begen_time." 00:00:00",$end_time." 23:59:59"));
            $flite_ids=array();
            foreach ($sf_id as $_fid) {
                // $k=$_fid->item_type.'-'.$_fid->item_id;
                $k=$_fid->item_id;
                $flite_ids[]=$k;
            }

            $f_id=DB::select("SELECT moi.item_id,moi.item_type
                FROM maintenance_out_list mol
                JOIN maintenance_out_item moi ON mol.id = moi.list_id
                join maintenance_out_order moo on moo.id=moi.order_out_id
                join orders o on o.order_id=moo.order_id
                WHERE mol.shop_id=?
                and mol.type =3
                AND mol.`status` = 1
                AND moi.`status` = 1
                and o.pay_time>? and o.pay_time<=?
                and o.status in(1018,1017,1217,1317,1417) 
                group by moi.item_id ",array($sc_user->shop_id,$begen_time." 00:00:00",$end_time." 23:59:59"));
            foreach ($f_id as $_fid) {
                // $k=$_fid->item_type.'-'.$_fid->item_id;
                $k=$_fid->item_id;
                $flite_ids[]=$k;
            }
            $flite_ids=array_unique($flite_ids);
            //获取 key_ids-flite_ids 结果
            $ids=array_diff($key_ids,$flite_ids);
            $ids[]=0;
            //获取指定ID 在制定时间的入库记录
            $sql='select * from (
                    SELECT
                        msi.*,
                        md. NAME data_name,
                        ms. NAME suppliername
                        
                    FROM
                        maintenance_storage_item msi
                    LEFT JOIN maintenance_storage_list msl ON msl.id = msi.list_id
                    LEFT JOIN maintenance_supplier ms ON ms.id = msl.supplier
                    LEFT JOIN maintenance_datebase md ON msi.data_id = md.id
                    WHERE
                        msi.shop_id =?
                    AND msi.STATUS = 1
                    AND msi.type = 1 
                    and msl.implement_time<=?) as temp 
                    where  temp.item_id IN ("'.implode('","',$ids).'")  LIMIT ?, ?';
            $count_sql='select count(1) count from (
                    SELECT
                        msi.*,
                        md. NAME data_name,
                        ms. NAME suppliername
                    FROM
                        maintenance_storage_item msi
                    LEFT JOIN maintenance_storage_list msl ON msl.id = msi.list_id
                    LEFT JOIN maintenance_supplier ms ON ms.id = msl.supplier
                    LEFT JOIN maintenance_datebase md ON msi.data_id = md.id
                    WHERE
                        msi.shop_id =?
                    AND msi.STATUS = 1
                    AND msi.type = 1 
                    and msl.implement_time<=?) as temp 
                    where  temp.item_id IN ("'.implode('","',$ids).'")';            
            $s_arr=DB::select($sql,array($sc_user->shop_id,$end_time." 23:59:59",($page-1)*$page_size,$page_size));
            $counts_arr=DB::select($count_sql,array($sc_user->shop_id,$end_time." 23:59:59")); 
            $finally_arr=array();        
            foreach ($s_arr as $item) {                
                // if($item->item_type==0){
                $item_info=SupplyItem::getCacheItemInfo($item->item_id);
                // }else{
                //     $item_info=SupplyItemNonStandard::getCacheItemInfo($item->item_id);
                // }
                $part_classification = Report::get_part_classification($item_info->st_classifi_id);
                $finally_arr[]=array(
                    "suppliername"=>$item->suppliername,
                    "date_name"=>$item->data_name,
                    "list_id"=>$item->list_id,
                    "code"=>$item_info->code,
                    "old_code"=>$item_info->old_code,
                    "car_model"=>$item_info->car_model_comments,
                    "name"=>$item->name,
                    "model"=>$item_info->model,
                    "unit"=>$item_info->unit,
                    "number"=>$item->number,
                    "current_number"=>$item->current_number,
                    "subject_name"=>$item_info->subject_name,
                    "scf_id"=>$item_info->st_classifi_id,
                    "scf_name"=>$item_info->scf_name,
                    "location"=>$item->location,
                    "tax_purchase_price"=>$item->tax_purchase_price,
                    "tax_purchase_subtotal"=>$item->tax_purchase_subtotal,
                    "item_brand_name"=>$item_info->brand_name,
                    "item_series_name"=>$item_info->series_name,
                    "item_model_name"=>$item_info->model,
                    "item_specification"=>$item_info->specification,
                    "item_pack_unit"=>$item_info->pack,
                    "item_sale_unit"=>$item_info->unit,
                    "car_model_comments"=>$item_info->car_model_comments,
                    "item_name"=>$item_info->name,
                    "scf_two_id"=>$part_classification['level_2_id'],
                    "scf_two_name"=>$part_classification['level_2_name'],
                );              
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$counts_arr[0]->count,"moo_info"=>$finally_arr));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "unsalable_inquiry_detail", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    
    /**
     * @Author:      lyt
     * @DateTime:  2017-09-15 10:10:34
     * @Description: 滞销查询汇总
     */
    public function unsalable_inquiry_total(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'begen_time' => 'required',
                'end_time' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $begen_time=Input::get("begen_time");
            $end_time=Input::get("end_time");
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);

            //查出结束时间期末 存在库存的耗材
            $mwos=MaintenanceWarehouseOrderStock::where("shop_id",$sc_user->shop_id)->where("date",$end_time)->where("number",">",0)->get();
            // $mwos=MaintenanceWarehouse::where("shop_id",$sc_user->shop_id)->where("number",">",0)->get();
            $key_ids=$key_value=array();
            foreach ($mwos as $_mwos) {
                $k=$_mwos->item_id;
                $key_ids[]=$k;
            }
                // $key_value[$k]=$_mwos;
            //查找时间段内有过销售 记录的耗材信息
            $sf_id=DB::select("SELECT moi.item_id,moi.item_type
                FROM maintenance_out_list mol
                JOIN maintenance_out_item moi ON mol.id = moi.list_id
                WHERE
                 mol.shop_id=?
                and mol.type =1 
                AND mol.methed= 3
                AND mol.`status` = 1
                AND moi.`status` = 1
                and mol.implement_time>? and mol.implement_time<=?                
                group by moi.item_id",array($sc_user->shop_id,$begen_time." 00:00:00",$end_time." 23:59:59"));
            $flite_ids=array();
            foreach ($sf_id as $_fid) {
                $k=$_fid->item_id;
                $flite_ids[]=$k;
            }

            $f_id=DB::select("SELECT moi.item_id,moi.item_type
                FROM maintenance_out_list mol
                JOIN maintenance_out_item moi ON mol.id = moi.list_id
                join maintenance_out_order moo on moo.id=moi.order_out_id
                join orders o on o.order_id=moo.order_id
                WHERE mol.shop_id=?
                and mol.type =3
                AND mol.`status` = 1
                AND moi.`status` = 1
                and o.pay_time>? and o.pay_time<=?
                and o.status in(1018,1017,1217,1317,1417) 
                group by moi.item_id",array($sc_user->shop_id,$begen_time." 00:00:00",$end_time." 23:59:59"));
            foreach ($f_id as $_fid) {
                $k=$_fid->item_id;
                $flite_ids[]=$k;
            }
            $flite_ids=array_unique($flite_ids);
            //获取 key_ids-flite_ids 结果
            $ids=array_diff($key_ids,$flite_ids);
            $ids[]=0;
            //获取指定ID 在制定时间库存
            $sql='select * from (SELECT
                    mwoo.*
                FROM      maintenance_warehouse_order_stock mwoo
                WHERE     shop_id = ?
                AND date = ?) as temp where item_id in("'.implode('","',$ids).'")  LIMIT ?, ?';
            $count_sql='select count(1) count from (SELECT
                    mwoo.*
                FROM      maintenance_warehouse_order_stock mwoo
                WHERE     shop_id = ?
                AND date = ?) as temp where item_id in("'.implode('","',$ids).'")';            
            $s_arr=DB::select($sql,array($sc_user->shop_id,$end_time,($page-1)*$page_size,$page_size));
            $counts_arr=DB::select($count_sql,array($sc_user->shop_id,$end_time)); 
            $finally_arr=array();        
            foreach ($s_arr as $item) {                
                // if($item->item_type==0){
                $item_info=SupplyItem::getCacheItemInfo($item->item_id);
                // }else{
                //     $item_info=SupplyItemNonStandard::getCacheItemInfo($item->item_id);
                // }
                $part_classification = Report::get_part_classification($item_info->st_classifi_id);
                $finally_arr[]=array(
                    "old_code"=>$item_info->old_code,
                    "car_model"=>$item_info->car_model_comments,
                    "code"=>$item_info->code,
                    "name"=>$item_info->name,
                    "model"=>$item_info->model,
                    "unit"=>$item_info->unit,
                    "number"=>$item->number,
                    "subject_name"=>$item_info->subject_name,
                    "scf_id"=>$item_info->st_classifi_id,
                    "scf_name"=>$item_info->scf_name,
                    "item_brand_name"=>$item_info->brand_name,
                    "item_series_name"=>$item_info->series_name,
                    "item_model_name"=>$item_info->model,
                    "item_specification"=>$item_info->specification,
                    "item_pack_unit"=>$item_info->pack,
                    "item_sale_unit"=>$item_info->unit,
                    "car_model_comments"=>$item_info->car_model_comments,
                    "item_name"=>$item_info->name,
                    "scf_two_id"=>$part_classification['level_2_id'],
                    "scf_two_name"=>$part_classification['level_2_name'],
                );             
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$counts_arr[0]->count,"moo_info"=>$finally_arr));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "unsalable_inquiry_total", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }



    /**
     * @Author:      lyt
     * @DateTime:  2017-09-15 10:52:09
     * @Description: 备货参考
     */
    public function stock_reference(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'number' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $number=Input::get("number");
            $begen_time=date('Y-m-01', strtotime('-'.$number.' month'));
            $end_time=date('Y-m-t', strtotime('-1 month'));//结束时间
           

            //查出当前时间有库存的
            $mwos=MaintenanceWarehouse::where("shop_id",$sc_user->shop_id)->where("number",">",0)->get();
            $key_ids=$key_value=array();
            foreach ($mwos as $_mwos) {
                $k=$_mwos->item_type.'-'.$_mwos->item_id;
                $key_ids[]=$k;
            }
                // $key_value[$k]=$_mwos;
            //查找时间段内有过销售 记录的耗材信息
            $f_id=DB::select("SELECT moi.item_id,moi.item_type
                FROM maintenance_out_list mol
                JOIN maintenance_out_item moi ON mol.id = moi.list_id
                join maintenance_out_order moo on moo.id=moi.order_out_id
                join orders o on o.order_id=moo.order_id
                WHERE mol.shop_id=?
                and mol.type =3
                AND mol.`status` = 1
                AND moi.`status` = 1
                and o.pay_time>? and o.pay_time<=?
                and o.status in(1018,1017,1217,1317,1417) 
                group by moi.item_id,moi.item_type",array($sc_user->shop_id,$begen_time." 00:00:00",$end_time." 23:59:59"));
            $flite_ids=array();
            foreach ($f_id as $_fid) {
                $k=$_fid->item_type.'-'.$_fid->item_id;
                $flite_ids[]=$k;
            }
            //获取 key_ids-flite_ids 结果
            $ids=array_unique(array_merge($key_ids,$flite_ids));
            //查找当前的耗材存库成本
            $sotck_sql="select item_type,item_id,sum(current_number) number,sum(current_number*tax_purchase_price) amount from maintenance_storage_item msi
            where msi.shop_id=? and msi.status=1 and msi.type=1  group by msi.item_type,msi.item_id";
            $s_item=DB::select($sotck_sql,array($sc_user->shop_id));
            $item_stock=array();
            foreach ($s_item as $_s_item) {
                $k=$_s_item->item_type.'-'.$_s_item->item_id;
                $item_stock[$k]=$_s_item;
            }
            //查找库存上下限
            $warn_sql="SELECT item_id,item_type,max_number,mim_number FROM `maintenance_warehouse_warn` where shop_id=? and `status`=1";
            $warn_item=DB::select($warn_sql,array($sc_user->shop_id));
            $item_warn=array();
            foreach ($warn_item as $_s_item) {
                $k=$_s_item->item_type.'-'.$_s_item->item_id;
                $item_warn[$k]=$_s_item;
            }
            //构造 这几个月的每个耗材的数组
            $mouth_array=array();
            for($i=1; $i <=$number ; $i++) { 
                $temp_begen_time=date('Y-m-01 00:00:00', strtotime('-'.$i.' month'));
                $temp_end_time=date('Y-m-t 23:59:59', strtotime('-'.$i.' month'));//结束时间
                $date_str=date('Y-m', strtotime($temp_end_time));
                //服务订单维修出库
                $service_order_out_data = ReportDateReocrd::get_service_order_out_data_for_jxc($sc_user->shop_id,0,$temp_begen_time,$temp_end_time);
                //零售订单销售出库
                $sale_order_out_data = ReportDateReocrd::get_sale_order_out_data_for_jxc($sc_user->shop_id,0,$temp_begen_time,$temp_end_time);
                $return_stireage_date = ReportDateReocrd::get_return_storage_data_for_jxc($sc_user->shop_id,0,$temp_begen_time,$temp_end_time);
                foreach ($ids as $_key) {  
                    $o=isset($service_order_out_data[$_key]['number'])?$service_order_out_data[$_key]['number']:0;
                    $s=isset($sale_order_out_data[$_key]['number'])?$sale_order_out_data[$_key]['number']:0;
                    $r=isset($return_stireage_date[$_key]['number'])?$return_stireage_date[$_key]['number']:0;
                    $temp=$o+$s-$r;
                    if(isset($mouth_array[$_key])){
                        $mouth_array[$_key][$date_str]=$temp;
                    }else{
                        $mouth_array[$_key]=array($date_str=>$temp);
                    }
                }
            }
            //够造货位数组
            $location_sql="SELECT item_type,item_id,location FROM `supply_location` where shop_id=?";
            $location=DB::select($location_sql,array($sc_user->shop_id));
            $location_arr=array();
            foreach ($location as $_s_item) {
                $k=$_s_item->item_type.'-'.$_s_item->item_id;
                $location_arr[$k]=$_s_item->location;
            }

            $finally_arr=array();
            foreach ($ids as $key) {
                $date=explode("-",$key);
                // if($date[0]==0){
                
                $item_info=SupplyItem::getCacheItemInfo($date[1]);
                // }else{
                //     $item_info=SupplyItemNonStandard::getCacheItemInfo($date[1]);
                // }
                $part_classification = Report::get_part_classification($item_info->st_classifi_id);
                $finally_arr[]=array(
                    "old_code"=>$item_info->old_code,
                    "car_model"=>$item_info->car_model_comments,
                    "code"=>$item_info->code,
                    "subject_name"=>$item_info->subject_name,
                    "scf_id"=>$item_info->st_classifi_id,
                    "scf_name"=>$item_info->scf_name,
                    "item_brand_name"=>$item_info->brand_name,
                    "item_series_name"=>$item_info->series_name,
                    "item_model_name"=>$item_info->model,
                    "item_specification"=>$item_info->specification,
                    "item_pack_unit"=>$item_info->pack,
                    "item_sale_unit"=>$item_info->unit,
                    "car_model_comments"=>$item_info->car_model_comments,
                    "number"=>isset($item_stock[$key])?$item_stock[$key]->number:0,
                    "amount"=>isset($item_stock[$key])?$item_stock[$key]->amount:0,
                    "max_warn"=>isset($item_warn[$key])?$item_warn[$key]->max_number:0,
                    "min_warn"=>isset($item_warn[$key])?$item_warn[$key]->mim_number:0,
                    'level_1_id' => $part_classification['level_1_id'],
                    'level_1_name' => $part_classification['level_1_name'],
                    'level_2_id' => $part_classification['level_2_id'],
                    'level_2_name' => $part_classification['level_2_name'],
                    'level_3_id' => $part_classification['level_3_id'],
                    'level_3_name' => $part_classification['level_3_name'],
                    "location"=>isset($location_arr[$key])?$location_arr[$key]:"",
                    "nouth"=>isset($mouth_array[$key])?$mouth_array[$key]:array(),
                    "item_name"=>$item_info->name,
                );  
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>sizeof($ids),"moo_info"=>$finally_arr));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "stock_reference", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}